<?php

namespace app_supplier\controllers;

use app_supplier\models\BillToReceive;
use app_supplier\models\ClearingItem;
use app_supplier\models\Dealer;
use app_supplier\models\DealerMaterialType;
use app_supplier\models\DealerPayAccount;
use app_supplier\models\DealerStaff;
use app_supplier\models\MaterialType;
use app_supplier\models\WarehousingHeader;
use app_supplier\models\WarehousingItem;
use yii\data\ActiveDataProvider;
use yii;
class InventoryController extends BaseController
{
    protected function responseAjax()
    {
        Yii::$app->response->format=yii\web\Response::FORMAT_JSON;
    }

    public function actionIndex()
    {
        $this->view->title = '库存管理';
        return $this->render('index');
    }
    public function actionQuery()
    {
        $this->view->title = '库存查询';

        return $this->render('query');
    }
    public function actionWarehousing_list()
    {
        $this->view->title = '出库入库查询';

        return $this->render('warehousing_list');

    }

    /**
     * 新增入库
     * @return string
     */
    public function actionEnter_warehouse()
    {
//        if (!$this->affiliate->isLogged()) {
//            $this->session->data['redirect'] = $this->url->link('affiliate/enter_warehouse', '', 'SSL');
//            $this->redirect($this->url->link('affiliate/login', '', 'SSL'));
//        }

        $dealer_id = $this->dealer_id;
        //获取所有配件信息
        $materials = Dealer::query()
            ->select(['name','id'])
            ->from('material')
            ->all();
        //获取该经销商配件信息
        $dealer_material = Dealer::query()
            ->select('DISTINCT (m.id),m.`name`')
            ->from('dealer_material_type dmt')
            ->innerJoin('material m','dmt.material_id=m.id')
            ->where("dmt.dealer_id={$dealer_id}")
            ->all();
        //获取该经销商所有员工工种
        $workers_job = DealerStaff::query()
            ->select('job')
            ->from('dealer_staff')
            ->where(['dealer_id'=>$dealer_id])
            ->groupBy('job')
            ->all();
        //获取所有员工信息
        $workers = DealerStaff::findAll(['dealer_id'=>$dealer_id,'status'=>1]);  //name : $workers[0]->name
        //获取登录人name和job
//        $account = $this->affiliate->getAccount();
        $account_name = '小王';
        $account_job = DealerStaff::findOne(['dealer_id'=>$dealer_id,'name'=>$account_name]);

        //判断是否打印
//        $this->data['issetPrint'] = $this->issetPrint("config_warehouse_is_print");

        $issetPrint = $this->issetPrint;
        $this->view->title = '新增入库';

        return $this->render('enter_warehouse',['materials'=>$materials,'dealer_material'=>$dealer_material,'workers_job'=>$workers_job,'workers'=>$workers,'account'=>['name'=>$account_name,'job'=>$account_job],'issetPrint'=>$issetPrint]);
    }

    /**
     * 新增出库
     * @return string
     */
    public function actionOut_warehouse()
    {
        $this->view->title = '新增出库';
        return $this->render('out_warehouse');
    }

    /**
     * 获取入库配件的品牌
     * @return string
     */
    public function actionBrand()
    {
        $id = Yii::$app->request->get('id', '');
        $isStoreBrand = Yii::$app->request->get('isStoreBrand', '');
        $dealer_id = $this->dealer_id;

        if (empty($id)){
            $data = array();
        } else{
            if(empty($isStoreBrand)){
                $data = MaterialType::query()
                    ->select('brand')
                    ->from('material_type')
                    ->where("material_id={$id}")
                    ->groupBy('brand')
                    ->all();
            }else{
                $data = MaterialType::query()
                    ->select('mt.brand')
                    ->from('material_type mt')
                    ->innerJoin('dealer_material_type dmt','dmt.material_type_id=mt.id')
                    ->where("mt.material_id={$id} AND dmt.dealer_id={$dealer_id}")
                    ->groupBy('brand')
                    ->all();
            }
        }
        $this->responseAjax();
        return json_encode($data);
    }

    /**
     * 获取所有入库配件的列表
     * @return array
     */
    public function actionGetallmaterialdata()
    {
        $this->responseAjax();
        $page = Yii::$app->request->get('page',1);
        $pageCount = isset($_GET['count']) ? (empty($_GET['count']) ? 20 : $_GET['count']) : 2;
        $isStoreMaterial = intval(Yii::$app->request->get('isStoreMaterial',0));

        $material_id = Yii::$app->request->post('material','');
        $brand = Yii::$app->request->post('brand','');
        $key = Yii::$app->request->post('key','');
        $_where = " 1=1 ";

        if (!empty($material_id))
            $_where .= " and mt.material_id={$material_id}";
        if (!empty($brand))
            $_where .= " and mt.brand='{$brand}'";
        if (!empty($key))
            $_where .= " and mt.type like '%{$key}%'";
        $dealer_id = $this->dealer_id;

        $result = MaterialType::getAllMaterialType($_where, '', '', $page, $pageCount, $dealer_id, $isStoreMaterial);
        $result['pages'] = yii\widgets\LinkPager::widget([
            'pagination' => $result['pages'],
            'maxButtonCount'=> 9,
            'firstPageLabel' => '首页',
            'nextPageLabel' => '下一页',
            'prevPageLabel' => '上一页',
            'lastPageLabel' => '末页']);
        return $result;
    }

    /**
     * 入库数提交数据处理
     * @return array
     */
    public function actionWarehousingenter()
    {
        $this->responseAjax();

        $dealer_id = $this->dealer_id;
        $enterWareHouseData = Yii::$app->request->post('postData',null);
        $isAllocate = Yii::$app->request->post('is_allocate',null);

        $chooseSelling = intval($enterWareHouseData['choose_selling']);

        $header_number = "RKD" . $dealer_id . date("ymd");
        //判断是否已经选择了操作人员，如果没有则记录当前登录人员名字
        if($enterWareHouseData['operator'] == null){
//            $a = $this->affiliate->getAccount();
            $enterWareHouseData['operator'] = '小王';
        }
        $warehousing_header = array(
            'header_number' => $header_number,
            'source_type' => 4,
            'dealer_id' => $dealer_id,
            'operation' => intval($enterWareHouseData['operation']),
            'total_price' => $enterWareHouseData['total'],
            'store_id' => intval($enterWareHouseData['dealer_id']),
            'date_added' => date('Y-m-d H:i:s',strtotime($enterWareHouseData['date'])),
            'operator' => $enterWareHouseData['operator'],
            'description' => $enterWareHouseData['remark']
        );
        $WarehousingHeader = new WarehousingHeader();
        $WarehousingHeader->attributes = $warehousing_header;
        if ($WarehousingHeader->validate() && $id = $WarehousingHeader->save()) {

        }
        $insertRet = WarehousingHeader::insertOne($warehousing_header);
        if($insertRet != 1)
            return ['msg'=>'添加warehousing_header表记录失败！','flag'=>false];

//        $last_id = $this->db->getLastId();
        $last_id = 18650;//rand(0,1000);
        $header_number .= sprintf("%03d", $last_id);
        $updateRet = WarehousingHeader::updateAll(['header_number' => $header_number],'id='.$last_id);
        if ($updateRet != 1)
            return ['msg'=>'更新warehousing_header表中的header_number失败！','flag'=>false];

        foreach ($enterWareHouseData['items'] as $item) {
            $selling_price = floatval($item['selling_price']);
            if(empty($selling_price))
                $selling_price = '';        //如果为空，表示没有设置售价
            $warehousing_item = array(
                'header_number' => $header_number,
                'material_id' => $item['material_id'],
                'material_type_id' => $item['material_type_id'],
                'material_type_name' => $item['material_type'],
                'sku' => $item['sku'],
                'price' => $item['price'],
                'purchase_price' => $selling_price,
                'amount' => $item['quantity'],
                'subtotal_price' => $item['subtotal']
            );
            //添加或者更新门店材料库存
            $ret = WarehousingItem::insertOne($warehousing_item);
            if ($ret != 1)
                return ['msg'=>'添加warehousing_item表记录失败！','flag'=>false];
        }
        //判断是否为调拨入库
        if ($isAllocate == 1)
            return ['flag'=>false];

        foreach ($enterWareHouseData['items'] as $item) {
            $selling_price = floatval($item['selling_price']);
            if(empty($selling_price))
                $selling_price = 0;
            $storeMT = DealerMaterialType::findOne(['material_type_id'=>$item['material_type_id'],'material_id'=>$item['material_id'],'dealer_id'=>$dealer_id]);
            if (!empty($storeMT)) {
                $stock = intval($storeMT['stock']);
                $stock = $stock + intval($item['quantity']);

                //移动加权平均价格 和 售价
                $smt_id = $storeMT['id'];
                $smt_stock = $storeMT['stock'];
                $smt_price = $storeMT['price'];
                $smt_selling_price = floatval($storeMT['sale_price']);
                $new_price = $item['price'];
                $avg_price = (floatval($smt_price) * intval($smt_stock) + floatval($new_price) * intval($item['quantity'])) / intval($stock);
                $avg_price = round($avg_price, 2);
                if ($chooseSelling == 1) {
                    if ($smt_selling_price != $selling_price) {
                        $rvl = DealerMaterialType::updateAll(['price' => $avg_price, "sale_price" => $selling_price, 'stock' => $stock, 'update_time' => time()],'id='.$smt_id);
                    } else {
                        $rvl = DealerMaterialType::updateAll(['price' => $avg_price, 'stock' => $stock, 'update_time' => time()],'id='.$smt_id);
                    }
                } else {
                    $rvl = DealerMaterialType::updateAll(['price' => $avg_price, 'stock' => $stock, 'update_time' => time()],'id='.$smt_id);
                }
                if (intval($rvl) < 1)
                    return ['msg'=>'更新store_material_type表记录失败！','flag'=>false];
            } else {
                if ($chooseSelling == 1) {
                    $dealer_material_type = array(
                        'material_id' => $item['material_id'],
                        'material_type_id' => $item['material_type_id'],
                        'dealer_id' => $dealer_id,
                        'price' => $item['price'],
                        'sale_price' => $selling_price,
                        'stock' => $item['quantity'],
                        'top_limit' => '',
                        'low_limit' => 5,
                        'status' => 1,
                        'date_added' => date('Y-m-d H:i:s',time()),
                        'date_modified' => date('Y-m-d H:i:s',time()),
                        'update_time' => time()
                    );
                } else {
                    $dealer_material_type = array(
                        'material_id' => $item['material_id'],
                        'material_type_id' => $item['material_type_id'],
                        'dealer_id' => $dealer_id,
                        'price' => $item['price'],
                        'stock' => $item['quantity'],
                        'top_limit' => '',
                        'low_limit' => 5,
                        'status' => 1,
                        'date_added' => date('Y-m-d H:i:s',time()),
                        'date_modified' => date('Y-m-d H:i:s',time()),
                        'update_time' => time()
                    );
                }
                $ret2 = DealerMaterialType::insertOne($dealer_material_type);
                if ($ret2 != 1)
                    return ['msg'=>'添加store_material_type表记录失败！','flag'=>false];
            }
        }

        return ['msg'=>'success！','data'=>['header_number' => $header_number],'flag'=>true];
    }

    /**
     * 新增入库/新增出库记录 结算页面
     * @return string
     */
    public function actionClearing()
    {
        $isReturn = Yii::$app->request->get('isReturn','');
        $header_number = Yii::$app->request->get('header_number','');
        $dealer_id = $this->dealer_id;//Yii::$app->request->get('dealer_id','');
        //调拨需要的参数
        $is_allocat = Yii::$app->request->get('is_allocat',0);
        $store_id = Yii::$app->request->get('store_id','');
        $total_price = Yii::$app->request->get('total_price','');
        //判断是否打印
        $issetPrint = $this->issetPrint;
        if($is_allocat == 2) {   //调拨店结算,改变订单状态
//            $this->load->model('chebao/dbtable');
//            $dbtb = $this->model_chebao_dbtable;
//            $dbtb->update('warehousing_header', array('status' => 1), "header_number = '".$data['header_number']."'");
        }
        $payaccount = DealerPayAccount::getFlowsAllPayAccount($dealer_id);

        return $this->renderAjax('clearing_warehouse',['isReturn'=>$isReturn,'header_number'=>$header_number,'dealer_id'=>$dealer_id,'is_allocat'=>$is_allocat,'store_id'=>$store_id,'total_price'=>$total_price,'issetPrint'=>$issetPrint,'payaccount'=>$payaccount,'info'=>['id'=>'','order_price'=>'','order_number'=>'']]);
    }

    /**
     * 新增入库/新增出库记录 结算功能
     * @return string
     */
    public function actionClearingwarehouse()
    {
        $this->responseAjax();
        $dealer_id = $this->dealer_id;

        $clearingData = Yii::$app->request->post('clearingData',null);
        $clearingData = str_replace("&quot;", '"', $clearingData);
        $clearingData = json_decode($clearingData, true);
        //如果是调拨
        if(isset($clearingData['store_id']))
            $store_id = $clearingData['store_id'];
        $clearing_item = array(
            'type' => 5,
            'account_type' => 1,
            'store_id' => $dealer_id,
            'order_number' => $clearingData['header_number'],
            'amount' => floatval($clearingData['pay_by_cash']) + floatval($clearingData['pay_by_bank']) + floatval($clearingData['pay_by_others']),
            'pay_by_cash' => $clearingData['pay_by_cash'],
            'pay_by_bank' => $clearingData['pay_by_bank'],
            'pay_by_bank_id' => $clearingData['pay_by_bank_id'],
            'pay_by_others' => $clearingData['pay_by_others'],
            'pay_by_others_id' => $clearingData['pay_by_others_id'],
            'discount' => $clearingData['pay_by_discount'],
            'date_added' => time(),
            'description' => $clearingData['presale_notes'],
        );
        $ret = ClearingItem::insertOne($clearing_item);
        if ($ret != 1)
            return ['msg'=>'添加clearing_item表记录失败','flag'=>false];

        //添加挂账记录
        if ((!empty($clearingData['receivable'])) || ($clearingData['receivable'] != 0)){
            $bill_to_receive = array(
                'type' => 2,
                'order_number' => $clearingData['header_number'],
                'store_id' => $dealer_id,
                'customer_id' => $clearingData['dealer_id'],   //供应商id
                'amount' => $clearingData['receivable'],       //挂账金额
                'remainder' => $clearingData['receivable'],    //剩余挂账金额
                'status' => 1,
                'date_added' => time(),
                'date_modified' => time()
            );
            $ret = BillToReceive::insertOne($bill_to_receive);
            if ($ret != 1)
                return ['msg'=>'添加bill_to_receive表记录失败','flag'=>false];
        }

        return ['msg'=>'success','flag'=>true];
    }

    /**
     * 打印入库、出库单
     * @return string
     */
    public function actionPrint_warehouse()
    {
        $this->init();

        $header_number = Yii::$app->request->get('header_number',null);
        $head = WarehousingHeader::findOne(['header_number'=>$header_number]);
        $dealer_id = $this->dealer_id;
        $delaer = Dealer::findOne(['dealer_id'=>$dealer_id]);
        $dealer_name = isset($delaer['dealer_name'])?$delaer['dealer_name']:'';
        $items = WarehousingHeader::query()
            ->select('warehousing_item.*, material.name ,material_type.brand')
            ->from('warehousing_item, material,material_type')
            ->where('warehousing_item.material_id=material.id
                AND  warehousing_item.material_type_id=material_type.id
                AND warehousing_item.header_number=\'' .$header_number. '\'')
            ->all();

        if(file_exists('@app_supplier/views/inventory/dealer_print/'.$dealer_id . '/warehousing_print.tpl'))
            return $this->renderPartial('dealer_print/'.$dealer_id.'warehousing_print',['items'=>$items,'dealer_name'=>$dealer_name,'head'=>$head]);
        else
            return $this->renderPartial('dealer_print/warehousing_print',['items'=>$items,'dealer_name'=>$dealer_name,'head'=>$head]);
    }

    public function actionList()
    {
        $this->view->title = '库存盘点';
        return $this->render('list');

    }

}
